package com.sh.controller;

import com.sh.common.BaseResult;
import com.sh.common.exception.BizException;
import com.sh.service.store.IOSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private IOSService ossService;

    @GetMapping("/buckets")
    public BaseResult buckets() {
        return BaseResult.success(ossService.listBuckets());
    }

    @GetMapping("/objects")
    public BaseResult listObjects(@RequestParam(value = "bucket", required = false) String bucket,
                                  @RequestParam(value = "keyword", required = false) String keyword,
                                  @RequestParam("prefix") String prefix) throws BizException {
        return BaseResult.success(ossService.listObjects(bucket, prefix, keyword));
    }

    @GetMapping("/download")
    public void download(@RequestParam(value = "bucket", required = false) String bucket,
                         @RequestParam("prefix") String prefix, HttpServletResponse res) throws IOException, BizException {
        InputStream inputStream = ossService.getObject(bucket, prefix);
        if (inputStream == null) {
            return;
        }
        String filename = new File(prefix).getName();
        res.setContentType("application/octet-stream");
        res.addHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream= res.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
    }

    @GetMapping("/signUrl")
    public BaseResult signUrl(@RequestParam(value = "bucket", required = false) String bucket,
                              @RequestParam("prefix") String prefix,
                              @RequestParam(value = "expires", required = false) Integer expires) {
        return BaseResult.success(ossService.signUrl(bucket, prefix, expires));
    }


}
